class VocabsController < ApplicationController
  #TODO: Is this the best/fastest way to do this?
  def recalculate_points(user, index)
    progress = user.user_lang[index].pr
    points = 0
    progress.each do |k, v|
      points += v - 50
    end
    user.pt = points
  end

  # GET /vocabs.json
  def index
    if params[:l] and params[:c]
      @vocabs = Vocab.all la: params[:l], cl: params[:c]
    else
      @vocabs = []
    end

    if params[:u] and (users = User.all un: params[:u]).length > 0
      user = users[0]
      progress = {}
      ul_index = nil
      user.user_lang.each.with_index do |ul, i|
        next unless ul.la == params[:l] and ul.cl == params[:c]
        progress = ul.pr
        ul_index = i
        @vocabs.each.with_index do |v, j|
          id = v.id.to_s
          progress[id] ||= 50
          @vocabs[j]['pr'] = progress[id]
        end
      end
      if ul_index
        user.user_lang[ul_index].pr = progress
        recalculate_points user, ul_index
      end
      user.save
    end

    respond_to do |format|
      #format.html # index.html.erb
      format.json { render json: @vocabs }
    end
  end

  # GET /vocabs/1
  # GET /vocabs/1.json
  #def show
  #  #TODO: Use POST

  #end
  #
  ## GET /vocabs/new
  ## GET /vocabs/new.json
  #def new
  #  @vocab = Vocab.new
  #
  #  respond_to do |format|
  #    format.html # new.html.erb
  #    format.json { render json: @vocab }
  #  end
  #end
  #
  ## GET /vocabs/1/edit
  #def edit
  #  @vocab = Vocab.find(params[:id])
  #end
  #
  # POST /vocabs
  # POST /vocabs.json
  #TODO: blatant misuse of POST
  def create
    ok = true

    user = User.all(un: params[:u])[0]
    #TODO: Fail if index is invalid
    index = user.user_lang.index { |ul| ul.la == params[:l] and ul.cl == params[:c] }
    parsed_json = ActiveSupport::JSON.decode(params[:v])
    parsed_json.each do |word|
      user.user_lang[index].pr[word['id']] = word['pr']
    end

    recalculate_points user, index
    ok = user.save

    respond_to do |format|
      format.json { render json: { ok: ok } }
    end
  end
  #
  ## PUT /vocabs/1
  ## PUT /vocabs/1.json
  #def update
  #  @vocab = Vocab.find(params[:id])
  #
  #  respond_to do |format|
  #    if @vocab.update_attributes(params[:vocab])
  #      format.html { redirect_to @vocab, notice: 'Vocab was successfully updated.' }
  #      format.json { head :ok }
  #    else
  #      format.html { render action: "edit" }
  #      format.json { render json: @vocab.errors, status: :unprocessable_entity }
  #    end
  #  end
  #end
  #
  ## DELETE /vocabs/1
  ## DELETE /vocabs/1.json
  #def destroy
  #  @vocab = Vocab.find(params[:id])
  #  @vocab.destroy
  #
  #  respond_to do |format|
  #    format.html { redirect_to vocabs_url }
  #    format.json { head :ok }
  #  end
  #end
end
